import React from 'react'
import RcDialog from 'rc-dialog'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import addEventListener from 'rc-util/lib/Dom/addEventListener'
import { Icon, Button } from 'antd'

let mousePosition
export const destroyFns = []

const getClickPosition = (e) => {
	mousePosition = {
		x: e.pageX,
		y: e.pageY,
	};
	// 100ms 内发生过点击事件，则从点击位置动画展示
	// 否则直接 zoom 展示
	// 这样可以兼容非点击方式展开
	setTimeout(() => (mousePosition = null), 100);
};

// 只有点击事件支持从鼠标位置动画展开
if (typeof window !== 'undefined' && window.document && window.document.documentElement) {
	addEventListener(document.documentElement, 'click', getClickPosition);
}

export default class Dialog extends React.Component {
	static defaultProps = {
		prefixCls: 'x-dialog',
		width: 520,
		transitionName: 'zoom',
		maskTransitionName: 'fade',
		confirmLoading: false,
		visible: false,
		okType: 'primary',
		okButtonDisabled: false,
		cancelButtonDisabled: false,
	};
	static propTypes = {
		prefixCls: PropTypes.string,
		onOk: PropTypes.func,
		onCancel: PropTypes.func,
		okText: PropTypes.node,
		cancelText: PropTypes.node,
		centered: PropTypes.bool,
		width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		confirmLoading: PropTypes.bool,
		visible: PropTypes.bool,
		align: PropTypes.object,
		footer: PropTypes.node,
		title: PropTypes.node,
		closable: PropTypes.bool,
	};
	handleCancel = (e) => {
		const onCancel = this.props.onCancel;
		if (onCancel) {
			onCancel(e);
		}
	};
	handleOk = (e) => {
		const onOk = this.props.onOk;
		if (onOk) {
			onOk(e);
		}
	};
	renderFooter = () => {
		const {
			okText,
			okType,
			cancelText,
			confirmLoading
		} = this.props;
		return (
			<>
		        <Button onClick={this.handleCancel} {...this.props.cancelButtonProps}>
		          {cancelText || '关闭'}
		        </Button>
		        <Button
		          type={okType}
		          loading={confirmLoading}
		          onClick={this.handleOk}
		          {...this.props.okButtonProps}
		        >
		          {okText || '提交'}
		        </Button>
		    </>
		);
	};
	renderModal = (prefixCls) => {
		const {
			footer,
			visible,
			wrapClassName,
			centered,
			...restProps
		} = this.props;

		const defaultFooter = this.renderFooter();

		const closeIcon = (
			<span className={`${prefixCls}-close-x`}>
				<Icon className={`${prefixCls}-close-icon`} type={'close'} />
			</span>
		);

		return (
			<RcDialog
		        {...restProps}
		        prefixCls={prefixCls}
		        wrapClassName={classNames({ [`${prefixCls}-centered`]: !!centered }, wrapClassName)}
		        footer={footer === undefined ? defaultFooter : footer}
		        visible={visible}
		        mousePosition={mousePosition}
		        onClose={this.handleCancel}
		        closeIcon={closeIcon}
		      />
		);
	};

	render() {
		const { prefixCls } = this.props
		return <>{this.renderModal(prefixCls)}</>;
	}
}